import { AppConfig, ProjectConfig, AIProvider } from '../types';
import { ApiService } from './ApiService';
import { ProjectInfo } from '../types';

/**
 * 浏览器本地存储服务
 * 使用localStorage替代Electron的文件系统，同时集成后端API
 */
export class LocalStorageService {
  private static readonly CONFIG_KEY = 'ribao_app_config';
  private static readonly PROJECTS_KEY = 'ribao_projects';
  private static readonly SELECTED_PROJECT_KEY = 'ribao_selected_project';

  /**
   * 获取默认配置
   */
  static getDefaultConfig(): AppConfig {
    return {
      gitUsername: '',
      aiProvider: 'google' as AIProvider,
      apiKeys: {
        google: '',
        deepseek: '',
        tongyi: '',
        doubao: '',
        wenxin: ''
      },
      excludePatterns: [
        'node_modules/**',
        '.git/**',
        'dist/**',
        'build/**',
        '*.log',
        '.env*'
      ],
      projects: []
    };
  }

  /**
   * 加载配置
   */
  static loadConfig(): { success: boolean; data?: AppConfig; error?: string } {
    try {
      const configStr = localStorage.getItem(this.CONFIG_KEY);
      if (!configStr) {
        const defaultConfig = this.getDefaultConfig();
        this.saveConfig(defaultConfig);
        return { success: true, data: defaultConfig };
      }
      
      const config = JSON.parse(configStr) as AppConfig;
      // 合并默认配置，确保新字段存在
      const mergedConfig = { ...this.getDefaultConfig(), ...config };
      return { success: true, data: mergedConfig };
    } catch (error) {
      return { 
        success: false, 
        error: `加载配置失败: ${error instanceof Error ? error.message : '未知错误'}` 
      };
    }
  }

  /**
   * 保存配置
   */
  static saveConfig(config: AppConfig): { success: boolean; error?: string } {
    try {
      localStorage.setItem(this.CONFIG_KEY, JSON.stringify(config, null, 2));
      return { success: true };
    } catch (error) {
      return { 
        success: false, 
        error: `保存配置失败: ${error instanceof Error ? error.message : '未知错误'}` 
      };
    }
  }

  /**
   * 获取项目列表
   */
  static getProjects(): ProjectConfig[] {
    try {
      const projectsStr = localStorage.getItem(this.PROJECTS_KEY);
      return projectsStr ? JSON.parse(projectsStr) : [];
    } catch (error) {
      console.error('获取项目列表失败:', error);
      return [];
    }
  }

  /**
   * 保存项目列表
   */
  static saveProjects(projects: ProjectConfig[]): { success: boolean; error?: string } {
    try {
      localStorage.setItem(this.PROJECTS_KEY, JSON.stringify(projects, null, 2));
      return { success: true };
    } catch (error) {
      return { 
        success: false, 
        error: `保存项目列表失败: ${error instanceof Error ? error.message : '未知错误'}` 
      };
    }
  }

  /**
   * 添加项目
   */
  static async addProject(path: string, name: string, description?: string): Promise<{ success: boolean; data?: ProjectConfig; error?: string }> {
    console.log(`[LocalStorage] 添加项目: ${name} (${path})`);
    
    try {
      // 先检查本地是否已存在
      const localProjects = this.getProjects();
      console.log(`[LocalStorage] 当前本地项目数量: ${localProjects.length}`);
      
      const existingProject = localProjects.find(p => p.path === path);
      if (existingProject) {
        console.warn(`[LocalStorage] 项目已存在: ${path}`);
        return { success: false, error: '项目已存在' };
      }

      // 调用后端API添加项目
      console.log(`[LocalStorage] 调用后端API添加项目...`);
      const apiResult = await ApiService.projects.add(name, path, description);
      console.log(`[LocalStorage] API响应:`, apiResult);
      
      if (!apiResult.success || !apiResult.data) {
        console.error(`[LocalStorage] API添加项目失败:`, apiResult.error);
        return { success: false, error: apiResult.error || '添加项目失败' };
      }

      // 转换API返回的ProjectInfo为ProjectConfig
      const newProject: ProjectConfig = {
        id: apiResult.data.id,
        name: apiResult.data.name,
        path: apiResult.data.path,
        description: apiResult.data.description,
        addedAt: apiResult.data.addedAt
      };
      console.log(`[LocalStorage] 新项目对象:`, newProject);

      // 同步到本地存储
      localProjects.push(newProject);
      const saveResult = this.saveProjects(localProjects);
      console.log(`[LocalStorage] 保存到本地存储结果:`, saveResult);
      
      if (saveResult.success) {
        console.log(`[LocalStorage] 项目添加成功: ${newProject.name}`);
        return { success: true, data: newProject };
      } else {
        console.error(`[LocalStorage] 保存到本地存储失败:`, saveResult.error);
        return saveResult;
      }
    } catch (error) {
      console.error(`[LocalStorage] 添加项目异常:`, error);
      return { 
        success: false, 
        error: `添加项目失败: ${error instanceof Error ? error.message : '未知错误'}` 
      };
    }
  }

  /**
   * 删除项目
   */
  static async removeProject(projectId: string): Promise<{ success: boolean; error?: string }> {
    try {
      // 调用后端API删除项目
      const apiResult = await ApiService.projects.remove(projectId);
      if (!apiResult.success) {
        return { success: false, error: apiResult.error || '删除项目失败' };
      }

      // 同步删除本地存储
      const projects = this.getProjects();
      const filteredProjects = projects.filter(p => p.id !== projectId);
      return this.saveProjects(filteredProjects);
    } catch (error) {
      return { 
        success: false, 
        error: `删除项目失败: ${error instanceof Error ? error.message : '未知错误'}` 
      };
    }
  }

  /**
   * 获取当前选中的项目
   */
  static getSelectedProject(): ProjectConfig | null {
    try {
      const selectedStr = localStorage.getItem(this.SELECTED_PROJECT_KEY);
      return selectedStr ? JSON.parse(selectedStr) : null;
    } catch (error) {
      console.error('获取选中项目失败:', error);
      return null;
    }
  }

  /**
   * 设置当前选中的项目
   */
  static setSelectedProject(project: ProjectConfig | null): { success: boolean; error?: string } {
    try {
      if (project) {
        localStorage.setItem(this.SELECTED_PROJECT_KEY, JSON.stringify(project));
      } else {
        localStorage.removeItem(this.SELECTED_PROJECT_KEY);
      }
      return { success: true };
    } catch (error) {
      return { 
        success: false, 
        error: `设置选中项目失败: ${error instanceof Error ? error.message : '未知错误'}` 
      };
    }
  }

  /**
   * 检测可用的API密钥
   */
  static detectApiKeys(): { provider: AIProvider; available: boolean }[] {
    const config = this.loadConfig();
    if (!config.success || !config.data) {
      return [];
    }

    const providers: AIProvider[] = ['google', 'deepseek', 'tongyi', 'doubao', 'wenxin'];
    return providers.map(provider => ({
      provider,
      available: !!(config.data!.apiKeys[provider]?.trim())
    }));
  }

  /**
   * 清除所有数据
   */
  static clearAll(): { success: boolean; error?: string } {
    try {
      localStorage.removeItem(this.CONFIG_KEY);
      localStorage.removeItem(this.PROJECTS_KEY);
      localStorage.removeItem(this.SELECTED_PROJECT_KEY);
      return { success: true };
    } catch (error) {
      return { 
        success: false, 
        error: `清除数据失败: ${error instanceof Error ? error.message : '未知错误'}` 
      };
    }
  }

  /**
   * 导出配置
   */
  static exportConfig(): { success: boolean; data?: string; error?: string } {
    try {
      const config = this.loadConfig();
      if (!config.success || !config.data) {
        return {
          success: false,
          error: '无法加载配置数据'
        };
      }
      
      const exportData = {
        config: config.data,
        projects: this.getProjects(),
        selectedProject: this.getSelectedProject(),
        exportedAt: new Date().toISOString(),
        version: '1.0.0'
      };
      
      return { 
        success: true, 
        data: JSON.stringify(exportData, null, 2) 
      };
    } catch (error) {
      return { 
        success: false, 
        error: `导出配置失败: ${error instanceof Error ? error.message : '未知错误'}` 
      };
    }
  }

  /**
   * 导入配置
   */
  static importConfig(configData: string): { success: boolean; error?: string } {
    try {
      const importData = JSON.parse(configData);
      
      if (importData.config) {
        const saveConfigResult = this.saveConfig(importData.config);
        if (!saveConfigResult.success) {
          return saveConfigResult;
        }
      }
      
      if (importData.projects) {
        const saveProjectsResult = this.saveProjects(importData.projects);
        if (!saveProjectsResult.success) {
          return saveProjectsResult;
        }
      }
      
      return { success: true };
    } catch (error) {
      return { 
        success: false, 
        error: `导入配置失败: ${error instanceof Error ? error.message : '未知错误'}` 
      };
    }
  }

  /**
   * 从后端同步项目列表到本地存储
   */
  static async syncProjectsFromBackend(): Promise<{ success: boolean; error?: string }> {
    try {
      const apiResult = await ApiService.projects.getAll();
      if (!apiResult.success || !apiResult.data) {
        return { success: false, error: apiResult.error || '同步项目失败' };
      }

      // 转换API返回的ProjectInfo[]为ProjectConfig[]
      const projects: ProjectConfig[] = apiResult.data.map(project => ({
        id: project.id,
        name: project.name,
        path: project.path,
        description: project.description,
        addedAt: project.addedAt
      }));

      return this.saveProjects(projects);
    } catch (error) {
      return {
        success: false,
        error: `同步项目失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
    }
  }

  /**
   * 获取项目作者列表
   */
  static async getProjectAuthors(projectPath: string): Promise<{ success: boolean; data?: string[]; error?: string }> {
    try {
      const apiResult = await ApiService.projects.getAuthors(projectPath);
      return {
        success: apiResult.success,
        data: apiResult.data,
        error: apiResult.error
      };
    } catch (error) {
      return {
        success: false,
        error: `获取项目作者失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
    }
  }

  /**
   * 获取项目总提交数
   */
  static async getProjectTotalCommits(projectPath: string): Promise<{ success: boolean; data?: number; error?: string }> {
    try {
      const apiResult = await ApiService.projects.getTotalCommits(projectPath);
      return {
        success: apiResult.success,
        data: apiResult.data,
        error: apiResult.error
      };
    } catch (error) {
      return {
        success: false,
        error: `获取项目提交数失败: ${error instanceof Error ? error.message : '未知错误'}`
      };
    }
  }
}